<?php
class Backend_Articles_Controller extends Backend_Controller_Crud_Vc
{
	/**
	 * (non-PHPdoc)
	 * @see Backend_Controller_Crud_Vc::indexAction()
	 */
	public function indexAction()
	{
		parent::indexAction();
		$this->_resource->addJs('/js/app/system/Topics.js', 3);
	}
	/**
	 * (non-PHPdoc)
	 * @see Backend_Controller_Crud::listAction()
	 */
	public function listAction()
	{
		$pager = Request::post('pager' , 'array' , array());
		$filter = Request::post('filter' , 'array' , array());
		$query = Request::post('search' , 'string' , false);
		
		$dataModel = Model::factory('articles');
		$vc = Model_Vc::getInstance();
		
		$fields = array(
				'id' , 
				'title' , 
				'code' , 
				'main_topic' , 
				'allow_comments',
				'allow_votes',
				'published' , 
				'published_version' , 
				'date_created' , 
				'date_updated'
		);
		$topicsModel = Model::factory('topics');

		$data = $dataModel->getListVc(
			$pager , $filter , $query , $fields , 'user' , 'updater' ,
			array(
				array(
					'joinType'=>'joinLeft',
					'table'=>array('tp'=>$topicsModel->table()),
					'condition'=>'main_topic = tp.id',
					'fields'=>array('topic_title'=>'title')
				)
			)
		);
		
		if(empty($data))
			Response::jsonSuccess(array() , array(
					'count' => 0
			));
		
		$ids = array();
		foreach($data as $k => $v)
			$ids[] = $v['id'];
		
		$maxRevisions = $vc->getLastVersion('articles' , $ids);
		
		foreach($data as $k => &$v)
			if(isset($maxRevisions[$v['id']]))
				$v['last_version'] = $maxRevisions[$v['id']];
			else
				$v['last_version'] = 0;
		
		Response::jsonSuccess($data , array(
				'count' => $dataModel->getCount($pager , $filter , $query)
		));
	}

	/**
	 * Check code Action
	 */
	public function checkCodeAction()
	{
		$id = Request::post('id' , 'int' , 0);
		$code = Request::post('code' , 'string' , false);
		$code = Filter::filterValue('pagecode' , $code);
		
		$model = Model::factory('articles');
		
		if($model->checkUnique($id , 'code' , $code))
			Response::jsonSuccess(array('code' => $code));
		else
			Response::jsonError($this->_lang->SB_UNIQUE);
	}
}